package com.kitchen.util;

import com.kitchen.config.DatabaseConfig;
import com.kitchen.exception.DatabaseException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库工具类
 * 封装数据库操作，提供连接管理和资源释放
 */
public class DatabaseUtil {
    
    /**
     * 获取数据库连接
     */
    public static Connection getConnection() {
        try {
            return DatabaseConfig.getInstance().getConnection();
        } catch (SQLException e) {
            throw new DatabaseException("获取数据库连接失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 关闭资源
     */
    public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void close(Connection conn, PreparedStatement pstmt) {
        close(conn, pstmt, null);
    }
}

